package com.xxl.sso.server.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.dao.UserDao;
import com.xxl.sso.server.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao,UserInfo> implements UserService {

    private static List<UserInfo> mockUserList = new ArrayList<>();
    static {
        for (int i = 0; i <5; i++) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserid(1000+i);
            userInfo.setUsername("user" + (i>0?String.valueOf(i):""));
            userInfo.setPassword("123456");
            mockUserList.add(userInfo);
        }
    }

    @Override
    public ReturnT<UserInfo> findUser(String username, String password) {

        if (username==null || username.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "请输入用户名.");
        }
        if (password==null || password.trim().length()==0) {
            return new ReturnT<UserInfo>(ReturnT.FAIL_CODE, "请输入密码.");
        }

        // mock user  (模拟数据)
        // for (UserInfo mockUser: mockUserList) {
        //     if (mockUser.getUsername().equals(username) && mockUser.getPassword().equals(password)) {
        //         return new ReturnT<UserInfo>(mockUser);
        //     }
        // }
        //思路：根据用户名查询出是否存在用户，将传入的password经过md5加密后再与这个用户的password对比
        //1. 加密密码
        String pwd = SecureUtil.md5(password);
        //2. 验证用户是否存在
        UserInfo userInfo = this.getOne(new QueryWrapper<UserInfo>().eq("username", username));
        if(userInfo != null){
            if(pwd.equals(userInfo.getPassword())){
                return new ReturnT<>(userInfo);
            }
        }
        return new ReturnT<>(ReturnT.FAIL_CODE, "用户名或密码无效.");
    }


}
